import axios from "axios"
import router from "@/router/index";
import store from "@/store";
const errorHandle = (status,info) => {
    switch(status){
      case 400:
        console.log("语义有误");
        break;
      case 401:
        console.log("服务器认证失败");
        break;
      case 403:
        console.log("服务器拒绝访问");
        break;
      case 404:
        console.log("地址错误");
        break;
      case 500:
        console.log("服务器遇到意外");
        break;
      case 502:
        console.log("服务器无响应");
        break;
      default:
        console.log(info);
        break;
     }
  }
const instance = axios.create({
    timeout:5000
})

instance.interceptors.request.use(
    config => {
        let token = localStorage.getItem('token')
        //请求前获取token给后端校验
        if(token){
          config.headers.Authorization = token
        }
        return config
    },
    error=>{
        return Promise.reject(error)
    }
)


instance.interceptors.response.use(
  response => {

      if(response.status < 300){
          return Promise.resolve(response)
      }else {
          return Promise.reject(response)
      }

  },
  error => {
    // 修复这里：使用error.response而不是response
    // if(error.response && error.status === 403 && error.response.data.status=='false'){

    //   localStorage.removeItem('token')
    //   store.state.user.isLogin=false
    //   router.push('/login')
    // }
    if(error.response && error.response.status === 401){

      localStorage.removeItem('token')
      localStorage.removeItem('username')
      store.commit('setIsLogin', false)  // 使用commit而不是直接修改state
      store.commit('setUserName', '')
      router.push('/login')
    }
    // const {response} = error
    //   if(response){
    //       errorHandle(response.status, response.info)
    //   } else {
    //     console.log('网络请求中断')
    // }
    return Promise.reject(error)
  }
)



export default instance